import asyncio
import os

import shutil

from bs4 import BeautifulSoup as bs

from utils.httpClient import HttpClient

BASE_URL = "https://pvp.qq.com"
HERO_LIST = "/web201605/js/herolist.json"

BASE_IMAGE_PATH = "images/王者荣耀"

hc = HttpClient()


async def download_img(ename, index):
    # 英雄高清壁纸图片
    url = f"https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/{ename}/{ename}-bigskin-{index}.jpg"
    return await hc.get(url, parse_json=False)


async def fetch_hero(ename=None, cname=None, skin_name=None, **kwargs):
    skins = await get_skins_by_heroid(ename)
    parent_path = f"{BASE_IMAGE_PATH}/{cname}"
    if not os.path.exists(parent_path):
        os.makedirs(parent_path)
    print(ename, cname, skins)
    for index, skin in enumerate(skins):
        image = await download_img(ename, index+1)
        with open(f"{parent_path}/{skin}.jpg", 'wb') as f:
            f.write(image)

async def get_skins_by_heroid(ename):
    """
    :param ename: 英雄id
    :return: 英雄对应皮肤名称列表
    """
    # 英雄对应详情页
    url = f"{BASE_URL}/web201605/herodetail/{ename}.shtml"
    data = await hc.get(url, parse_json=False, encoding="gbk")
    soup = bs(data, features="html.parser")
    ul = soup.find("ul", class_="pic-pf-list")
    skin_str = ul['data-imgname']
    skins = skin_str.split('|')
    return [skin.split('&')[0] for skin in skins]


async def main():
    if os.path.exists(BASE_IMAGE_PATH):
        shutil.rmtree(BASE_IMAGE_PATH)
    # 王者荣耀英雄列表
    hero_list = await hc.get(f"{BASE_URL}{HERO_LIST}")
    for hero in hero_list:
        await fetch_hero(**hero)
    await hc.close()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


